package com.glsc.ngateway.platform.controller.itflow;

import com.glsc.ngateway.common.api.ldap.dto.LdapEhrDeptDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.ldap.resp.AppEhrResponse;
import com.glsc.ngateway.common.api.common.dto.PageQueryParamDto;
import com.glsc.ngateway.common.api.flowable.dto.task.config.FlowConfigDto;
import com.glsc.ngateway.common.api.flowable.dto.task.config.FlowConfigSearchDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.enums.itflow.FlowConfigValueTypeEnum;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.itflow.config.ItFlowConfigService;
import com.glsc.ngateway.platform.vo.FlowTaskParamPreVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xuchang
 */
@RestController
@RequestMapping(value = "/it/flow/config")
@Api(value = "流程配置", tags = {"流程配置"})
public class FlowConfigController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ItFlowConfigService flowConfigService;

    @Resource
    private IFeignLdapService iFeignLdapService;

    @Resource
    private UserService userService;

    @ApiOperation(value = "查询配置", notes = "流程配置")
    @PostMapping("/search")
    public PlatformResponse<Page<FlowConfigDto>> query(@RequestBody PageQueryParamDto<FlowConfigSearchDto> queryParam) throws Exception {
        return PlatformResponse.successData(flowConfigService.page(queryParam));
    }

    @ApiOperation(value = "删除配置", notes = "流程配置")
    @PostMapping("/delete")
    public PlatformResponse<Void> delete(@RequestBody FlowConfigDto param) {
        if (Objects.isNull(param.getId())) {
            throw PlatformException.error("缺少参数");
        }
        flowConfigService.delete(param.getId());
        return PlatformResponse.successMsg("删除成功");
    }

    @ApiOperation(value = "添加或修改", notes = "流程配置")
    @PostMapping(value = "/addOrUpdate")
    public PlatformResponse<Void> addOrUpdate(@RequestBody FlowConfigDto flowConfig) throws Exception {
        flowConfig.setValue(flowConfig.getValue().stream().filter(Objects::nonNull).collect(Collectors.toList()));
        //处理配置值相关信息
        switch (FlowConfigValueTypeEnum.seek(flowConfig.getValueType())) {
            case DEPARTMENT:
                if (CollectionUtils.isNotEmpty(flowConfig.getValue())) {
                    List<String> deps = flowConfig.getValue().stream().map(v -> {
                        int depId = Integer.parseInt(v);
                        AppEhrResponse<List<LdapEhrDeptDto>> resp = iFeignLdapService.getAllDept();
                        if (Objects.isNull(resp) || !resp.isSuccess()) {
                            logger.error("操作失败, ehr调用异常{}", resp.getErrorMsg());
                            throw PlatformException.error("操作失败，查询部门信息失败");
                        }
                        LdapEhrDeptDto dep = resp.getData().stream().filter(d -> d.getDepid() == depId).findFirst().orElseThrow(() -> PlatformException.error("未找到部门信息"));
                        return dep.getDtitle();
                    }).collect(Collectors.toList());
                    flowConfig.setValue(deps);
                }
                break;
        }
        flowConfigService.addOrUpdate(flowConfig);
        return PlatformResponse.successMsg("操作成功");
    }

    @ApiOperation(value = "预览创建流程", notes = "预览创建流程")
    @GetMapping(value = "/preViewCreateFlow")
    public PlatformResponse<FlowTaskParamPreVo> preViewCreateFlow(@RequestParam String processDefKey, @RequestParam String user) {
        return PlatformResponse.successData(flowConfigService.preViewCreateFlow(processDefKey, user));
    }
}
